package jjn.round2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-06-10 19:24
 */
public class LeetCode39_CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, new ArrayList<>(), result, 0);
        return result;
    }
    
    private void backtrack(int[] candidates, int target, int sum, List<Integer> path, List<List<Integer>> result, int startIndex) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            if (sum + candidates[i] > target) {
                break;
            }
            path.add(candidates[i]);
            backtrack(candidates, target, sum + candidates[i], path, result, i);
            path.remove(path.size() - 1);
        }
    }
}
